package org.wanda.pv.controller.business;

import com.sun.org.apache.xalan.internal.xsltc.runtime.ErrorMessages_zh_CN;
import org.apache.poi.xwpf.converter.core.IURIResolver;
import org.apache.poi.xwpf.converter.xhtml.DefaultContentHandlerFactory;
import org.apache.poi.xwpf.converter.xhtml.IContentHandlerFactory;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.wanda.pv.config.FileProperties;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.framework.constant.AttachmentType;
import org.wanda.pv.model.business.Mark;
import org.wanda.pv.model.business.Attachment;
import org.wanda.pv.model.business.MarkExaminesContent;
import org.wanda.pv.model.business.MarkFileRe;
import org.wanda.pv.model.hy.HyUserInfo;
import org.wanda.pv.service.business.MarkService;
import org.wanda.pv.service.file.FileUploadService;
import org.wanda.pv.util.*;
import sun.awt.geom.AreaOp;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/business/mark")
@SuppressWarnings("all")
public class MarkController {
    private Logger log = LoggerFactory.getLogger(MarkController.class);
    @Autowired
    private MarkService markService;
    @Autowired
    private Dao dao;
    @Autowired
    private FileUploadService uploadService;
    @Autowired
    private FileProperties properties;


    @RequestMapping("/changeOptimization")
    @ResponseBody
    public Object changeOptimization(Long markId,Integer state){

        try{
            Mark mark = markService.fetch(markId);
            mark.setIsOptimization(state);
            markService.updateIgnoreNull(mark);
            return Result.success("success","操作成功!");
        } catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","服务器内部错误!");
        }


    }

    @RequestMapping("/wordDownload")
    public void wordDownload(Long attachmentId, HttpServletResponse response,HttpServletRequest request) throws Exception {
        try {
            Attachment attachment = dao.fetch(Attachment.class, attachmentId);
            File file = new File(attachment.getServerPath());
            String fileName = attachment.getName();
            String ext = attachment.getExName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(attachment.getServerPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            fileName+=ext;
            // 设置response的Header
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes(), "ISO-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }


    }


    @RequestMapping("/wordToHtml")
    public void wordToHtml(HttpServletRequest request, HttpServletResponse response,Long attachmentId){
        Attachment attachment = dao.fetch(Attachment.class, attachmentId);

        InputStream fis = null;

        response.setContentType("text/html; charset=UTF-8");
        try {

            fis = new FileInputStream(attachment.getServerPath());
            XWPFDocument document = new XWPFDocument(fis);
            final String imgUrl = "/wandaPV/file/imageLoader?attachmentId="+attachmentId+"&imageId=";
            XHTMLOptions options = XHTMLOptions.create().URIResolver(new IURIResolver(){

                @Override
                public String resolve(String uri) {
                    int ls = uri.lastIndexOf('/');
                    if (ls >= 0)
                        uri = uri.substring(ls+1);
                    return imgUrl+uri;
                }});
            OutputStream out = response.getOutputStream();

            IContentHandlerFactory factory = options.getContentHandlerFactory();
            if (factory == null) {
                factory = DefaultContentHandlerFactory.INSTANCE;
            }
            options.setIgnoreStylesIfUnused(false);

            KWBXHTMLMapper mapper = new KWBXHTMLMapper(document, factory.create(out, null, options), options);
            out.flush();
            mapper.start();

        }
        catch(Exception ex) {
           // throw ex;
            log.error(ex.getMessage(),ex);
        }
        finally {
            if(fis != null) {
                try {
                    fis.close();
                }catch (Exception e){
                    log.error(e.getMessage(),e);
                }

            }
        }



    }




    @RequestMapping("/delMark")
    @ResponseBody
    public Object delMark(Long id) {
        try {
            Result result = markService.del(id);
            return result;
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error("服务器内部错误!");
        }

    }


    @RequestMapping("/markList")
    @ResponseBody
    public Object markList(Long drawingId) {
        List<Mark> markList =new ArrayList<>();
        List<MarkFileRe> markFileRes = dao.query(MarkFileRe.class,Cnd.where("hy_drawing_id","=",drawingId).and("delFlag", "=", 0));
        markFileRes.forEach(markFileRe -> {
            Mark mark = markService.fetch(Cnd.where("id", "=", markFileRe.getMarkId()).and("delFlag", "=", 0));
            dao.fetchLinks(mark, null);
            dao.fetchLinks(mark.getPoint(), null);
            markList.add(mark);
        });
        return Result.success("success", markList);

    }

    @RequestMapping("/updateMarkStatus")
    @ResponseBody
    public Object updateMarkStatus(Long id,boolean passed){
        try {
            Result result = markService.updateMarkStatus(id,passed);
            return result;
        } catch (Exception e) {
            return Result.error("fail", "服务器内部错误!");
        }
    }


    @RequestMapping("/create")
    @ResponseBody
    public Object create(HttpServletRequest request,
                         Long drawingId,
                         String description,
                         String site,
                         String imgStr,
                         Long pointId,
                         String projectFlowChildrenNodeId,
                         boolean passed
    ) {


        String access_token = HyUtil.getHyToken().getAccess_token();
        String userSimple = HyUtil.getUserSimple(access_token);
        HyUserInfo user = (HyUserInfo) request.getSession().getAttribute("userInfo");
        projectFlowChildrenNodeId = (String) request.getSession().getAttribute("projectFlowChildrenNodeId");
        Mark mark = null;
        try {
            mark = markService.create(drawingId, description, site, imgStr, pointId, user.getId(), projectFlowChildrenNodeId,passed);
            return Result.success("success", mark);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Result.error("fail", "服务器内部错误!");
        }

    }


    @RequestMapping("/markInfo")
    @ResponseBody
    public Object markInfo(Long markId) {
        try {
            Mark mark = markService.fetch(markId);
            dao.fetchLinks(mark, null);
            dao.fetchLinks(mark.getPoint(), null);
            mark.getTopics().forEach(item -> {
                dao.fetchLinks(item, null);
                dao.fetchLinks(item.getHyUserInfo(), null);
            });
            if (mark.getMarkExaminesContent()==null){
                MarkExaminesContent markExaminesContent = new MarkExaminesContent();
                mark.setMarkExaminesContent(markExaminesContent);
            }

            return Result.success("success", mark);
        } catch (Exception e) {
            throw e;
        }

    }

	@RequestMapping("/getMarkStatistics")
    @ResponseBody
	public Object getMarkStatistics(Long drawingId){
    	Map<String,Object> resultMap = new HashMap<>();
    	// 查询出图纸关联的所有标注id
		List<MarkFileRe> markFileReList = dao.query(MarkFileRe.class,Cnd.where("hy_drawing_id","=",drawingId).and("delFlag", "=", 0));
		int pass = 0;
		int noPass = 0;
		for (MarkFileRe markFileRe : markFileReList) {
			Mark mark = dao.fetch(Mark.class,Cnd.where("id","=",markFileRe.getMarkId()).and("delFlag", "=", 0));
			// 通过的判断，
			if (mark.isPassed() == true){
				pass = ++pass;
			} else {
				noPass = ++noPass;
			}
		}
		resultMap.put("markCount",markFileReList.size());
		resultMap.put("pass",pass);
		resultMap.put("noPass",noPass);
		return Result.success("success",resultMap);
	}
}



/*@RequestMapping("/upload")
    public Object upload(String path, String fileName, Long markId) throws Exception {
        // 正式上传至服务器
        //Map<String, Object> upload = uploadService.upload(path);

        try {
            Map<String, Object> upload = uploadService.upload_(path);
            String filePath = (String) upload.get("filePath");
            String extName = (String) upload.get("extName");
            Attachment attachment = new Attachment();
            attachment.setExName(extName);
            attachment.setMarkId(markId);
            attachment.setServerPath(filePath);
            attachment.setName(fileName);
            attachment.setType(AttachmentType.MARK);

            dao.insert(attachment);
            return Result.success("success", "操作成功!");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("fail", "服务器内部错误!");
        }


    }*/